package com.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.entity.Category;
import com.reggie.entity.Dish;
import com.reggie.entity.Setmeal;
import com.reggie.exception.CustomException;
import com.reggie.mapper.CategoryMapper;
import com.reggie.mapper.DishMapper;
import com.reggie.mapper.SetmealMapper;
import com.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @program: reggie
 * @author:
 * @create: 2022-09-27 22:04
 **/
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 删除菜品的分类，不能删除有关联数据的菜品
     * */
    @Override
    public void removeById(Long id) {
        //查询dish表中有没有相关联的菜品
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.eq(Dish::getCategoryId,id);
        Integer dishCount = dishMapper.selectCount(dishWrapper);
        if (dishCount>0){
            //有关联的数据，不能进行删除，抛出异常
            throw new CustomException("有菜品数据关联，删除失败");
        }
        //查询SetmealDish表中有没有相关联的套餐
        LambdaQueryWrapper<Setmeal> setmealDishWrapper = new LambdaQueryWrapper<>();
        setmealDishWrapper.eq(Setmeal::getCategoryId,id );
        Integer setmealCount = setmealMapper.selectCount(setmealDishWrapper);
        if (setmealCount>0){
            //有关联的数据，不能进行删除，抛出异常
            throw new CustomException("有套餐数据关联，删除失败");
        }
        //没有关联的数据直接调用父类的删除方法
        super.removeById(id);
    }
}
